#!/bin/bash

[ "$#" = "1" ] || { echo "Usage: $(basename "$0") filename_of_image"; exit 1; }

CWD=$(pwd)
TMPDIR=$(mktemp -d .tmp.XXXXXXXX)
mirror=http://mirrors.aliyun.com/alpine/latest-stable

# download rootfs
file=$(curl -SsL $mirror/releases/x86_64/latest-releases.yaml | grep -wm 1  file | awk '{print $2}')
if [ ! -f $file ]; then
	wget $mirror/releases/x86_64/$file
fi

tar xf $file -C $TMPDIR

# config rootfs
echo "$mirror/main" > $TMPDIR/etc/apk/repositories
echo "$mirror/community" >> $TMPDIR/etc/apk/repositories
echo "nameserver 114.114.114.114" > $TMPDIR/etc/resolv.conf
echo "Asia/Shanghai" > $TMPDIR/etc/timezone
echo "share /mnt/share 9p defaults 0 0" >> $TMPDIR/etc/fstab
chroot $TMPDIR /bin/mkdir -p /lib/modules
chroot $TMPDIR /bin/mkdir -p /mnt/share
chroot $TMPDIR /bin/sh -c "echo 'root:123456'|chpasswd"
chroot $TMPDIR /sbin/apk update
chroot $TMPDIR /sbin/apk add alpine-base
chroot $TMPDIR /sbin/apk add busybox-extras
chroot $TMPDIR /sbin/rc-update add devfs sysinit
chroot $TMPDIR /sbin/rc-update add dmesg sysinit
chroot $TMPDIR /sbin/rc-update add mdev sysinit
chroot $TMPDIR /sbin/rc-update add hwdrivers sysinit
chroot $TMPDIR /sbin/rc-update add modules boot
chroot $TMPDIR /sbin/rc-update add sysctl boot
chroot $TMPDIR /sbin/rc-update add hostname boot
chroot $TMPDIR /sbin/rc-update add bootmisc boot
chroot $TMPDIR /sbin/rc-update add syslog boot
chroot $TMPDIR /sbin/rc-update add mount-ro shutdown
chroot $TMPDIR /sbin/rc-update add killprocs shutdown
chroot $TMPDIR /sbin/rc-update add savecache shutdown
chroot $TMPDIR /sbin/rc-update add firstboot default
chroot $TMPDIR /sbin/rc-update add networking default
chroot $TMPDIR /sbin/rc-update add local default
chroot $TMPDIR /sbin/apk add tzdata
chroot $TMPDIR /bin/cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
chroot $TMPDIR /sbin/apk del tzdata
chroot $TMPDIR /sbin/apk cache clean

cat << "EOF" > $TMPDIR/etc/network/interfaces
auto lo
iface lo inet loopback

auto eth0

iface eth0 inet dhcp

EOF

cat << "EOF" > $TMPDIR/etc/local.d/telnetd.start
telnetd -l /bin/sh
EOF
chmod a+x $TMPDIR/etc/local.d/telnetd.start

cd $TMPDIR && find ./ | cpio -o -H newc | gzip > ${CWD}/${1}
cd $CWD && /bin/rm -r $TMPDIR
